﻿using System.Data;
using Oracle.DataAccess.Client;

namespace Generator.Selections.DataBase
{
    class ConnectionHandler
    {
        private ConnectionString _cs;
        public void SetConnectionString(string userName, string password, string dbName)
        {
            _cs = new ConnectionString
                {
                    UserName = userName,
                    Password = password,
                    DbName = dbName
                };
            if (_conn != null)
                _conn.ConnectionString = _cs.ToString();            
        }

        private OracleConnection _conn;
        public OracleConnection Connection
        {
            get
            {
                if (_conn == null)
                {
                    if (_cs == null)
                    {
                        return null;
                    }

                    _conn = new OracleConnection(_cs.ToString());                    
                }

                return _conn;
            }
        }

        private static ConnectionHandler _instance;

        private ConnectionHandler()
        {
        }

        public static ConnectionHandler Instance
        {
            get { return _instance ?? (_instance = new ConnectionHandler()); }
        }

        public string CheckConnection()
        {
            if (_cs == null)
                return "Connection string not set";

            var result = string.Empty;
            try
            {
                Connection.Open();
            }
            catch (OracleException ex)
            {
                result = ex.ToString();
            }
            finally
            {
                try
                {
                    if (_conn.State == ConnectionState.Open)
                        _conn.Close();
                }
                catch (OracleException ex1)
                {
                    result += System.Environment.NewLine + ex1;
                }
            }

            return result;
        }

    }
}
